import { defineStore } from "pinia";
import { store } from "@/store";
import { useUserStoreHook } from "@/store/modules/user";
import {
  addRepair,
  AddRepairInfo,
  TaskInfo,
  deleteRepair,
  getRepair,
  getTasks
} from "@/api/repair";
import { message } from "@/utils/message";

export type RepairType = {
  workId: number;
  workName: string;
  workIdentity: number;
  workPartId: number;
  workStatus: number;
  workPhone: string;
};

export type stateType = {
  repairManList: Array<RepairType>;
  repairList: Array<TaskInfo>;
  repairManTotal: number;
  repairTotal: number;
};

export const useRepairStore = defineStore({
  id: "pure-Repair",
  state: (): stateType => ({
    repairManList: [],
    repairManTotal: 0,
    repairList: [],
    repairTotal: 0
  }),
  actions: {
    async getRepairInfo(currentPage: number, pigeSize: number) {
      await getRepair({
        id: useUserStoreHook().manageId,
        currentPage,
        pigeSize
      }).then(data => {
        this.repairManTotal = data.total;
        this.repairManList = data.list;
      });
    },
    async getTaskInfo(currentPage: number, pigeSize: number) {
      await getTasks({
        id: useUserStoreHook().manageId,
        currentPage,
        pigeSize
      }).then(data => {
        this.repairTotal = data.total;
        this.repairList = data.list;
      });
    },
    async addRepairMan(data: AddRepairInfo) {
      await addRepair(data).then(() => {
        message("添加成功", { type: "success" });
        useRepairStoreHook().repairManList.push(data);
      });
    },
    async deleteRepairMan(data: Array<number>) {
      await deleteRepair(data).then(() => {
        message("删除成功", { type: "success" });
        const set = new Set();
        for (let i = 0; i < data.length; i++) set.add(data[i]);
        useRepairStoreHook().repairManList =
          useRepairStoreHook().repairManList.filter(x => !set.has(x.workId));
      });
    }
  }
});

export function useRepairStoreHook() {
  return useRepairStore(store);
}
